package com.atguigu.tingshu.user.api;

import com.atguigu.tingshu.common.annotation.CheckLogin;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Tag(name = "微信授权登录接口")
@RestController
@RequestMapping("/api/user/wxLogin")
@Slf4j
public class WxLoginApiController {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Operation(summary = "小程序授权登录")
    @GetMapping(value = "/wxLogin/{code}")
    public Result<Map<String, String>> wxLogin(@PathVariable("code") String code) {
        Map<String, String> map = userInfoService.wxLogin(code);
        return Result.ok(map);
    }

    /**
     * @Description 在这里我们可以从redis中获取,直接使用使用token从redis中查询(可能存在redis和数据库中数据不一致问题)
     * 或者也可以使用自定义注解,获取到userId,从数据库中直接查询(可以保证用户都是正确的)
     */
    @Operation(summary = "获取登录用户信息")
    @GetMapping(value = "/getUserInfo")
    public Result<UserInfoVo> getUserInfo(@RequestHeader("token") String token) {
        UserInfoVo userInfoVo = (UserInfoVo) redisTemplate.opsForValue().get(RedisConstant.USER_LOGIN_KEY_PREFIX + token);
        return Result.ok(userInfoVo);
    }

    @CheckLogin
    @Operation(summary = "更新用户信息")
    @PostMapping(value = "/updateUser")
    public Result updateUser(@RequestHeader("token") String token,
                             @RequestBody UserInfoVo userInfoVo) {
        userInfoService.updateUser(token, userInfoVo);
        return Result.ok();
    }

}
